package com.lowkeymvc.tag;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class lowkeyMVCIteratorTag extends BodyTagSupport {
 
	private Object list;
	private String name;
	private Iterator it;
	@Override
	public int doEndTag() throws JspException {
		if(bodyContent!=null){
			try {
				bodyContent.writeOut(pageContext.getOut());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return SKIP_BODY;
	};
	@Override
	public int doAfterBody() throws JspException {
		return continueIt(it);
	};
	@Override
	public int doStartTag() throws JspException {
		// TODO Auto-generated method stub
		if(null==it){
			return SKIP_BODY;
		}else {
			return continueIt(it);
		} 
	}
	
	private int continueIt(Iterator it){
		if(it.hasNext()){
			pageContext.setAttribute(name, it.next());
			return EVAL_BODY_AGAIN;
		}else {
			return SKIP_BODY;
		}
	}
	
	public Object getList() {
		return list;
	}
	public void setList(Object list) {
		if(list instanceof Collection){
			Collection tmp = (Collection) list;
			it = tmp.iterator();
		}
		this.list = list;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Iterator getIt() {
		return it;
	}
	public void setIt(Iterator it) {
		this.it = it;
	}
	
}
